﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Core;
using Entity;

namespace CSPTest.Admin
{
    public partial class Country : EntityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected override EntityDataSource EntitySource
        {
            get { return this.edsMain; }
        }

        protected override TextBox EntitySearchTxt
        {
            get { return this.SearchText; }
        }

        protected override Button EntityAddBtn
        {
            get { return this.BtnAdd; }
        }

        protected override Button EntityClearBtn
        {
            get { return this.BtnClear; }
        }

        protected override GridView EntityGrid
        {
            get { return gvMain; }
        }

        protected override DetailsView EntityDetails
        {
            get { return dvMain; }
        }

        //TODO: remove logic code to BL
        protected override void OnEntityDisabling(int entityKey)
        {
            using (var dc = new CSPEntities())
            {
                dc.Countries.First(p => p.CountryID == entityKey).Disabled = true;
                dc.SaveChanges();
            }
        }

        protected override string GetEntitySortExpression(string keyword)
        {
            return "(it.Name like N'%" + EntitySearchTxt.Text + "%')";
        }

        //TODO: remove logic code to BL
        protected override void OnEntityInserting(EntityDataSourceChangingEventArgs e)
        {
            var country = e.Entity as Entity.Country;

            var users = e.Context.CreateQuery<Entity.User>("[Users]");
            country.CreatedBy = users.First(p => p.Alias == this.User.Identity.Name);
            country.CreatedTime = DateTime.Now;
            country.LastModifiedBy = country.CreatedBy;
            country.LastModifiedTime = DateTime.Now;
        }

        //TODO: remove logic code to BL
        protected override void OnEntityUpdating(EntityDataSourceChangingEventArgs e)
        {
            var country = e.Entity as Entity.Country;

            var users = e.Context.CreateQuery<Entity.User>("[Users]");
            country.LastModifiedBy = users.First(p => p.Alias == this.User.Identity.Name);
            country.LastModifiedTime = DateTime.Now;
        }

    }
}
